import constant from "../utils/constants";
import {getChatTokenReq, sendBaseketballChatMsgReq, sendChatMsgReq} from "../apis/goApis";
import LocalStorageService from "../utils/LocalStorageService";

export const chat = {
    state: {
        chatWs: null,
        users: [],
        err: '',
        dialogues: [
            // {"c":1,"msg":"1","Viplevel":11,"Nickname":"allen4062","uid":"e974e90e-0223-481a-b89c-0e681b09b804"},
            // {"c":1,"msg":"1","Viplevel":21,"Nickname":"allen4062","uid":"e974e90e-0223-481a-b89c-0e681b09b804"},
            // {"c":1,"msg":"1","Viplevel":31,"Nickname":"allen4062","uid":"e974e90e-0223-481a-b89c-0e681b09b804"},
            // {"c":1,"msg":"1","Viplevel":41,"Nickname":"allen4062","uid":"e974e90e-0223-481a-b89c-0e681b09b804"},
            // {"c":1,"msg":"1","Viplevel":51,"Nickname":"allen4062","uid":"e974e90e-0223-481a-b89c-0e681b09b804"},

            // {uid: '587f1818-8cd0-4785-97ed-d8314b55f715', c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {uid: '587f1818-8cd0-4785-97ed-d8314b55f715', c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 3, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
            // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
        ],
        gifts: [
            // {
            //     c: 2,
            //     uid: localStorage.getItem('userid'),
            //     giftId: 1,
            //     giftnum: 10,
            //     tuid: localStorage.getItem('userid'),
            // },
        ],
        connected: false,
    },

    reducers: {
        setChatWs(state, payload) {
            return {
                ...state,
                chatWs: payload,
            }
        },

        setHistoryMsg(state, payload) {
            const history = payload.history
            if (history) {
                const dialogues = history.map(data => {
                    return JSON.parse(data.data)
                })
                return {
                    ...state,
                    dialogues,
                }
            } else {
                return {
                    ...state
                }
            }

        },

        setHeartbeatId(state, payload) {
            return {
                ...state,
                heartbeatId: payload,
            }
        },

        setChatWsEmpty(state, payload) {
            return {
                ...state,
                chatWs: null,
                heartbeatId: 0,
                users: [],
                dialogues: [
                    // {uid: '587f1818-8cd0-4785-97ed-d8314b55f715', c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {uid: '587f1818-8cd0-4785-97ed-d8314b55f715', c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 3, nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 3, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '名字想破头', Viplevel: '27', msg: '坐等最后一场球吧，按这个套路，猴年马月啊',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                    // {c: 1, Nickname: '派大星的邻居', Viplevel: '17', msg: '都散了吧散了吧',},
                ],
                gifts: [
                    // {
                    //     c: 2,
                    //     uid: localStorage.getItem('userid'),
                    //     giftId: 1,
                    //     giftnum: 10,
                    //     tuid: localStorage.getItem('userid'),
                    // },
                ],
            }
        },

        setNewUser(state, payload) {
            return {
                ...state,
                dialogues: [...state.dialogues, payload],
                users: [...state.users, payload],
            }
        },

        setUserLeave(state, payload) {
            const users = state.users
            const i = users.findIndex(user => user.id === payload.id)
            users.splice(i, 1)
            return {
                ...state,
                dialogues: [...state.dialogues, payload],
                users: users,
            }
        },

        setNewUserMsg(state, payload) {
            return {
                ...state,
                dialogues: [...state.dialogues, payload],
            }
        },

        setNewGift(state, payload) {
            return {
                ...state,
                gifts: [...state.gifts, payload,],
                dialogues: [...state.dialogues, payload,],
            }
        },

        setErrorCode(state, payload) {
            return {
                ...state,
                err: payload,
            }
        },
        setChatConnected(state, payload) {
            return {
                ...state,
                connected: true,
            }
        }
    },


    effects: (dispatch) => ({
        doEmptyWsErr(payload, rootState) {
            dispatch.chat.setErrorCode('')
        },

        async doGetChatToken(payload, rootState) {
            const resp = await getChatTokenReq(payload)
            return resp
            // handleResp(resp, dispatch, (data) => {
            //     console.log(data)
            //
            // })
        },

        async onConnectWs(payload, rootState) {
            // console.log(payload)
            const {
                ws,
                msg,
            } = payload
            // const resp = await

            // ws.onopen = () => {
            //     console.log('connect')
            // }



            // 聊天室请求建立步骤:
            // 1, /getchattoken params: {uid: string,} 获取 token 短链接
            // 2, 建立长连接实例 发送心跳包 "heart"
            // 3, 发送长连接登录消息
            // params: {act:string uid, frds: string[], hid:sring "login", quns:string [], token:string 聊天室token,}
            // 4, 收到验证消息
            // code: 0
            // data: {newmsg: []}
            // err: ""
            // hid: "rsplogin"
            // 5 发送消息加入直播消息
            // params: {hid:string 'joinzhibo', zhibo: int[] [比赛id],}
            // 6 收到加入直播回应
            // {
            //     code: 0
            //     data: {newmsg: [{zhibo: "3383254", msg: null}]}
            //     newmsg: [{zhibo: "3383254", msg: null}]
            //     err: ""
            //     hid: "rspjoinzhibo"
            // }
            // 7 发送消息 sendzhibomsg 短链接
            // params:
            // {
            //      uid, 用户id
            //      to, 填写比赛id
            //      propid, 礼物id 如果不是填 0
            //      propnum, 礼物数量 如果不是填 0
            //      game, 填写空字符串 ''
            //      usepacket, 是否是用背包
            //      nosave: 1, 是否保存在聊天记录
            //      上面参数可以参考盛鹏文档说明
            //      data: JSON.stringify(data), 把我们以前发送的消息格式转成字符串放在这个data里比如加入房间
            //             const data = {
            //                 c: 3,
            //                 uid,
            //                 nickname: userDetail.Nickname,
            //                 viplevel: userDetail.Viplevel,
            //                 vip: userDetail.Vip,
            //             }
            // }
            dispatch.chat.setChatWs(ws)
            ws.onopen = () => {
                const heartbeatId = heartbeat(ws)
                dispatch.chat.setHeartbeatId(heartbeatId)

                try {
                    // 加入房间
                    const data = JSON.stringify(msg)
                    ws.send(data)
                } catch (err) {
                    // const msg = JSON.parse(e.data)
                    const e = err.err
                    dispatch.global.globalError(constant.WsErrorCode[e])
                }
            }

            ws.onmessage = async (e) => {

                // console.log(e)
                try {
                    const message = JSON.parse(e.data)
                    // console.log(e)
                    if (message.err) {
                        const e = message.err
                        // Toast.fail(constant.WsErrorCode[e])
                        dispatch.chat.setErrorCode(e)
                        // dispatch.global.globalError(constant.WsErrorCode[e])
                        // ws.close()
                        // return

                    }
                    // const {c,} = message
                    //
                    // const cToAction = {
                    //     1: dispatch.chat.setNewUserMsg,
                    //     2: dispatch.chat.setNewGift,
                    //     3: dispatch.chat.setNewUser,
                    //     4: dispatch.chat.setUserLeave,
                    // }
                    // cToAction[c](message)

                    const {hid, code,} = message
                    if (hid === 'rsplogin') {
                        if (code === 0) {
                            const newHid = 'joinzhibo'
                            const zhibo = [String(rootState.game.currentGame.matchId)]
                            const data = JSON.stringify(({
                                hid: newHid,
                                zhibo,
                            }))
                            ws.send(data)
                        }
                    }

                    if (hid === 'rspjoinzhibo') {
                        const uid = LocalStorageService.get('uid')
                        if (code === 0 && uid) {
                            this.setChatConnected()
                            const propid = 0
                            const to = String(rootState.game.currentGame.matchId)
                            const propnum = 0
                            const game = ''
                            const usepacket = 0
                            const userDetail = rootState.user.userdetail
                            const data = {
                                c: 3,
                                uid,
                                nickname: userDetail.Nickname,
                                viplevel: userDetail.Viplevel,
                                vip: userDetail.Vip,
                            }
                            // const newmsg =
                            const params = {
                                uid,
                                to,
                                propid,
                                propnum,
                                game,
                                usepacket,
                                nosave: 1,
                                data: JSON.stringify(data),
                            }
                            sendChatMsgReq(params)
                        }
                        const history = message.data.newmsg[0].msg
                        dispatch.chat.setHistoryMsg({history,})
                    }

                    if (hid === 'msg') {

                        let data = JSON.parse(message.data.data)
                        // data.Name = data.name
                        data.Id = data.giftId
                        const c = data.c
                        data.data = message.data

                        const cToAction = {
                            1: dispatch.chat.setNewUserMsg,
                            2: dispatch.chat.setNewGift,
                            3: dispatch.chat.setNewUser,
                            4: dispatch.chat.setUserLeave,
                        }
                        // cToAction[c](message)
                        cToAction[c](data)
                    }
                } catch (err) {
                    console.log(err)
                }

            }

            dispatch.chat.setChatWs(ws)
        },

        onChatWsClose(payload, rootState) {
            const chatWs = rootState.chat.chatWs
            const id = rootState.chat.heartbeatId
            clearInterval(id)
            chatWs && chatWs.close()
            dispatch.chat.setChatWsEmpty()
        },
    })
}

export const heartbeat = (ws) => {
    const diff = 5000
    const heartId = setInterval(() => {
        ws.send('heart')
    }, diff)
    return heartId
}
